package com.example.chmextractor.controller;

import com.example.chmextractor.service.ChmExtractorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.nio.charset.StandardCharsets;

@Controller
public class ChmExtractorController {

    @Autowired
    private ChmExtractorService chmExtractorService;

    @GetMapping("/")
    public String index() {
        return "index";
    }

    @PostMapping("/extract")
    public ResponseEntity<ByteArrayResource> extractChm(@RequestParam("file") MultipartFile file) {
        try {
            String content = chmExtractorService.extractToText(file);
            
            // 准备下载的文件名
            String filename = file.getOriginalFilename();
            if (filename == null) {
                filename = "output.txt";
            } else {
                filename = filename.replaceAll("\\.chm$", "") + ".txt";
            }
            
            // 将内容转换为ByteArrayResource
            ByteArrayResource resource = new ByteArrayResource(content.getBytes(StandardCharsets.UTF_8));
            
            // 设置响应头
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + filename)
                    .contentType(MediaType.TEXT_PLAIN)
                    .contentLength(resource.contentLength())
                    .body(resource);
                    
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }
}
